<template>
  <div class="content-page">
    <div class="header flex justify-between items-center mb-8">
      <div class="search-filter-container flex items-center space-x-4">
        <input type="text" placeholder="搜索证书..." class="search-input border border-gray-300 rounded-md px-3 
        py-2 focus:outline-none focus:ring-blue-500 focus:border-blue-500" />
        <select class="filter-select border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
          <option value="all">全部类型</option>
          <!-- 这里可以添加更多筛选选项 -->
        </select>
        <button class="filter-button bg-blue-500 text-white rounded-md px-2 py-2 hover:bg-blue-600 focus:outline-none
         focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 ">筛选</button>
      </div>
      <el-button type="primary" @click="showDialog = true">上传认证</el-button>
    </div>

    <div class="certificate-gallery">
      <div class="certificate-container" v-for="(certificate, index) in certificates" :key="index">
        <h3>{{ certificate.name }}</h3>
        <img :src="certificate.photoMaterials" :alt="`Certificate Image ${index + 1}`" style="width: 400px; height: 200px">
        <div class="certificate-info">
          <p><strong>比赛名字:</strong> {{ certificate.competitionName }}</p>
          <p><strong>获奖级别:</strong> {{ certificate.competitionAwardLevelName }}</p>
          <p><strong>开始时间:</strong> {{ formatDate(certificate.competitionStartTime) }}</p>
          <p><strong>结束时间:</strong> {{ formatDate(certificate.competitionEndTime) }}</p>
          <p><strong>主办方:</strong> {{ certificate.competitionOrganizer }}</p>
          <p><strong>专业类型:</strong> {{ certificate.competitionType }}</p>
        </div>
        <div class="actions-container">
          <template v-if="certificate.status === 0">
            <span class="flex items-center gap-1 text-orange-500">
              <i class="fas fa-clock"></i>
              <span class="text-sm">待审核</span>
            </span>
          </template>
          <template v-if="certificate.status === 1">
            <span class="flex items-center gap-1 text-green-600">
              <i class="iconfont icon-gou1"></i>
              <span class="text-sm">审核通过</span>
            </span>
          </template>
          <template v-if="certificate.status === 2">
            <span class="flex items-center gap-1 text-red-600">
              <i class="iconfont icon-chacha"></i>
              <span class="text-sm">审核未通过</span>
            </span>
          </template>
          <button class="edit-button" @click="showEditDialog(certificate.id)">修改</button>
          <button class="delete-button" @click="confirmRemoveCertificate(certificate.id)">删除</button>
        </div>
      </div>
    </div>

    <div v-if="showDialog" class="dialog-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
      <div class="dialog-content bg-white rounded-tl-lg rounded-bl-lg w-[80vw] max-w-[800px] p-8">
        <div class="dialog-header mb-6">
          <h2 class="text-xl font-medium">提交比赛信息</h2>
        </div>

        <div class="dialog-body">
          <form @submit.prevent="handleSubmit">
            <div class="form-item mb-4">
              <label class="required-label block mb-2">比赛名称:</label>
              <el-select v-model="formData.competitionId" placeholder="请选择比赛" filterable :loading="loading"
                @change="handleCompetitionChange" class="w-full text-sm">
                <el-option v-for="item in competitions" :key="item.id" :label="item.competitionName" :value="item.id" />
              </el-select>
            </div>

            <div class="form-item mb-4">
              <label class="required-label block mb-2">获奖级别:</label>
              <el-select v-model="formData.level" placeholder="请先选择比赛" :disabled="!formData.competitionId"
                class="w-full text-sm">
                <el-option v-for="level in awardLevels" :key="level.id"
                  :label="`${level.competitionLevelName} - ${level.awardLevelName}`" :value="level.id" />
              </el-select>
            </div>

            <div class="form-item mb-4">
              <label class="required-label block mb-2">比赛类型:</label>
              <el-select v-model="formData.type" placeholder="请选择比赛类型" class="w-full text-sm">
                <el-option label="专业" value="与专业相关" />
                <el-option label="非专业" value="与专业不相关" />
              </el-select>
            </div>

            <div class="form-item mb-4">
              <label class="required-label block mb-2">比赛组织单位:</label>
              <el-input v-model="formData.organizer" placeholder="请输入组织名称" class="w-full text-sm" />
            </div>

            <div class="form-item mb-4">
              <label class="required-label block mb-2">比赛时间:</label>
              <div class="flex items-center gap-4">
                <el-date-picker v-model="formData.startTime" type="date" placeholder="选择开始时间" class="flex-1 text-sm" />
                <span class="text-gray-400">-</span>
                <el-date-picker v-model="formData.endTime" type="date" placeholder="选择结束时间" class="flex-1 text-sm" />
              </div>
            </div>

            <div class="form-item mb-4">
              <label class="required-label block mb-2">比赛描述:</label>
              <el-input v-model="formData.description" type="textarea" :maxlength="50" :rows="4" placeholder="请输入比赛描述性证明"
                show-word-limit class="w-full text-sm" />
            </div>

            <div class="form-item mb-6">
              <label class="required-label block mb-2">图片证明材料:</label>
              <div
                class="upload-area border-2 border-dashed border-gray-200 rounded-lg p-6 text-center cursor-pointer hover:border-blue-400 transition-colors"
                @click="triggerUpload">
                <el-icon class="text-gray-400 text-2xl mb-2">
                  <Plus />
                </el-icon>
                <input ref="fileInput" type="file" class="hidden" accept="image/*" @change="handleFileChange">
                <div class="text-gray-500 text-sm">点击或拖拽上传图片(需要重新上传图片)</div>
                <div class="text-gray-400 text-xs mt-1">图片尺寸规则:A4纸为准,大小不大于1M</div>
              </div>
              <div v-if="imagePreview" class="mt-4">
                <img :src="imagePreview" alt="预览图片" class="w-full h-auto rounded-lg" />
              </div>
            </div>

            <div class="dialog-footer flex justify-end gap-4">
              <el-button @click="handleCancel" class="!rounded-button whitespace-nowrap">返回</el-button>
              <el-button type="primary" @click="handleSubmit" :disabled="!isFormValid"
                class="!rounded-button whitespace-nowrap">
                提交
              </el-button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCompetition, deleteCompetition, getCompetitionList, getAwardLevels } from '@/api/student/certification/stuCompetition';
import axios from 'axios';
import { getToken } from '@/utils/auth';

// 日期格式化方法
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; 
};

const imagePreview = ref(null); 
const showDialog = ref(false);
const fileInput = ref(null);
const formData = ref({
  competitionId: '',
  level: '',
  type: '',
  startTime: '',
  endTime: '',
  organizer: '',
  description: '',
  file: null
});
const isFormValid = computed(() => {
  return formData.value.competitionId &&
    formData.value.level &&
    formData.value.type &&
    formData.value.startTime &&
    formData.value.endTime &&
    formData.value.organizer &&
    formData.value.description &&
    formData.value.file; 
});
const triggerUpload = () => {
  fileInput.value?.click();
};
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    formData.value.file = file;
    if (file.size > 1024 * 1024) {
      ElMessage.error('文件大小不能超过1M');
      formData.value.file = null;
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};
const handleSubmit = async () => {
  if (!isFormValid.value) {
    ElMessage.warning('请填写完整所有必填项');
    return;
  }
  const form = new FormData();
  form.append('images', formData.value.file);
  form.append('competitionDto', JSON.stringify({
    id: selectedCertificateId.value, 
    competitionId: formData.value.competitionId,
    competitionLevelId: formData.value.level,
    competitionType: formData.value.type,
    competitionStartTime: formData.value.startTime,
    competitionEndTime: formData.value.endTime,
    competitionOrganizer: formData.value.organizer,
    descMaterials: formData.value.description,
  }));
  try {
    const token = getToken();
    const response = await axios.post('http://localhost:8081/certificateAuthority/addCompetition', form, {
      headers: {
        'token': `${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log(response);
    if (response.data.code === 200) {
      ElMessage.success('提交成功');
      formData.value = {
        competitionId: '',
        level: '',
        type: '',
        startTime: '',
        endTime: '',
        organizer: '',
        description: '',
        file: null
      };
      imagePreview.value = null;
      showDialog.value = false;
      selectedCertificateId.value = null;
      fetchCertificates();
    } else {
      ElMessage.error(response.data.msg || '提交失败，请稍后重试');
      console.error('Backend error:', response.data);
    }
  } catch (error) {
    ElMessage.error('提交时发生错误');
    console.error(error);
  }
};
const handleCancel = () => {
  showDialog.value = false;
  formData.value = {
    competitionId: '',
    level: '',
    type: '',
    startTime: '',
    endTime: '',
    organizer: '',
    description: '',
    file: null
  };
  imagePreview.value = null;
  selectedCertificateId.value = null;
  ElMessage.info('已取消');
};
const certificates = ref([]);
const fetchCertificates = () => {
  getCompetition()
    .then(response => {
      certificates.value = response;
    })
    .catch(error => {
      ElMessage.error('查询数据时发生错误');
      console.error(error);
    });
};
onMounted(() => {
  fetchCertificates();
});
function confirmRemoveCertificate(id) {
  ElMessageBox.confirm(
    '您确定要删除这个比赛吗？此操作不可逆！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    removeCertificate(id);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}
function removeCertificate(id) {
  deleteCompetition(id)
    .then(response => {
      ElMessage.success('删除成功');
      fetchCertificates();
    })
    .catch(error => {
      ElMessage.error('删除失败');
      console.error(error);
    });
}
const competitions = ref([]);
const awardLevels = ref([]);
const loading = ref(false);
const selectedCertificateId = ref(null); 

watch(showDialog, async (newVal) => {
  if (newVal) {
    try {
      loading.value = true;
      const res = await getCompetitionList();
      competitions.value = res;
    } catch (error) {
      ElMessage.error('获取比赛列表失败');
    } finally {
      loading.value = false;
    }
  } else {
    awardLevels.value = [];
    formData.value.competitionId = '';
    formData.value.level = '';
  }
});
const handleCompetitionChange = async (competitionId) => {
  try {
    const res = await getAwardLevels({ competitionId });
    awardLevels.value = res;
  } catch (error) {
    ElMessage.error('获取获奖级别失败');
    awardLevels.value = [];
  }
};
function showEditDialog(id) {
  const certificate = certificates.value.find(cert => cert.id === id);
  if (certificate) {
    formData.value = {
      competitionId: certificate.competitionId,
      level: certificate.competitionLevelId,
      type: certificate.competitionType,
      startTime: certificate.competitionStartTime,
      endTime: certificate.competitionEndTime,
      organizer: certificate.competitionOrganizer,
      description: certificate.descMaterials,
      file: null 
    };
    selectedCertificateId.value = id;
    imagePreview.value = certificate.photoMaterials; 
    showDialog.value = true;
  }
}
</script>

<style scoped>
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.dialog-overlay {
  z-index: 1000;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  width: 90vw;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  background: #fff;
  border-radius: 1rem 0 0 1rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.dialog-content::-webkit-scrollbar {
  width: 8px;
}

.dialog-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 1rem;
}

.dialog-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 1rem;
}

.dialog-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.certificate-gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.5rem;
  justify-items: center;
}

.certificate-container {
  position: relative;
  border-radius: 1rem;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 1rem;
  text-align: center;
  width: 400px;
  /* max-width: px; */
  background-color: #fff;
}

h3 {
  font-size: 1.25rem;
  color: #333;
  margin-bottom: 0.5rem;
  white-space: nowrap; /* 防止换行 */
  overflow: hidden; /* 隐藏溢出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
}

img {
  display: block;
  margin: 0.1rem auto;
  border-radius: 0.5rem;
  width: 350px;
  height: 350px;
}

.certificate-info {
  text-align: left;
  margin-top: 0.15rem;
  overflow-wrap: break-word;
  word-break: break-all;
  max-width: 260px;
}

.certificate-info p {
  font-size: 1rem;
  color: #00796b;
  margin: 0.15rem 0;
  white-space: nowrap; /* 防止换行 */
  overflow: hidden; /* 隐藏溢出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
}

.actions-container {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  margin-top: 0.3rem;
  justify-content: flex-end;
}

.edit-button {
  background-color: #2196f3;
  color: white;
  border: none;
  padding: 0.3rem 0.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
  margin-right: 0.3rem;
  transition: background-color 0.3s ease;
}

.edit-button:hover {
  background-color: #1976d2;
}

.delete-button {
  background-color: red;
  color: white;
  border: none;
  padding: 0.3rem 0.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.delete-button:hover {
  background-color: darkred;
}

.search-input {
  width: 80%;
  max-width: 400px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px 12px;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.search-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
  border-color: #3b82f6;
}

.filter-select {
  width: auto;
  min-width: 150px;
  padding: 0.5rem 0.75rem;
  line-height: 1.25;
  border: 1px solid #ccc;
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

.filter-select:focus {
  outline: none;
  border-color: #3b82f6;
}

.filter-button {
  width: auto;
  min-width: 80px;
  padding: 0.5rem 1rem;
  line-height: 1.25;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.filter-button:hover {
  background-color: #1976d2;
}

.upload-area {
  transition: border-color 0.3s ease;
  border: 2px dashed #ccc;
  border-radius: 0.5rem;
  padding: 1rem;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #3b82f6;
}

.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: scale(1.05);
}
.certificate-info p {
  font-size: 1rem;
  color: #000; /* 现改为黑色#000 */
  margin: 0.15rem 0;
  white-space: nowrap; 
  overflow: hidden; 
  text-overflow: ellipsis; 
}


</style>